<?php

/**
 * 第三方登录 新浪微博 QQ 微信
 * ============================================================================
 * * 版权所有 20013-* 梅州络客网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.alork.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: index.php 17217 2013-10-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

$act  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'qq';

if($act == 'qq')
{
    $appid = '101221368';
    $appkey = 'c2cb027c4612da1af5c68edb7ff5ae1a';
    $callback = 'http://'.$_SERVER['HTTP_HOST'].'/connect.php?act=qq';

    require(ROOT_PATH . 'includes/qqapi.class.php');
    $info = new qqapi($appid,$appkey,$callback);
    if(!isset($_GET['code'])){
        $info->redirect_to_login();
    }else{
        $openid = $_SESSION['oauthId'] = $info->get_openid($_GET['code']);
        $_SESSION['oauthType'] = 'qq';
        if(!empty($openid)){
            $r = $db->getRow("SELECT `user_id`,`user_name`,`email`,`password` FROM {$ecs->table('users')} WHERE `qq_openid` = '$openid'");
            if(!empty($r)){
                /* 执行已绑定第三方登录 */
                oauthLogin($r);

                /* 登录成功跳转到首页 */
                header('location:index.php');
            }
            else
            {
                /* 回调绑定页面 */
                $smarty->assign('direct_login', 'connect.php?act=direct_login&oauthType=qq');
                $smarty->display('bind.dwt');
            }
        } else {
            $info->redirect_to_login();
        }
    }
}


if($act == 'weibo')
{
    $appid = '1881969712';
    $appkey = '5905e553e75d650bd93ad559a2d5138a';
    $callback = 'http://'.$_SERVER['HTTP_HOST'].'/connect.php?act=weibo';//回调地址

    require(ROOT_PATH . 'includes/saetv2.ex.class.php');
    $apiInfo = new SaeTOAuthV2($appid, $appkey);

    if(isset($_GET['code'])){
        $keys = array();
        $keys['code'] = $_GET['code'];
        $keys['redirect_uri'] = $callback;
        try {
            $token = $apiInfo->getAccessToken('code', $keys);
        } catch (OAuthException $e) {
            /* 如果获取不成功，则重新切换到微博登录页 */
            header("Location:".$apiInfo->getAuthorizeURL($callback));
            exit;
        }
        $c = new SaeTClientV2($appid, $appkey, $token['access_token']);
        $uid_get = $c->get_uid();  //获取授权用户的UID
        $me = $c->show_user_by_id($uid_get['uid']);  //返回用户资料

        $_SESSION['oauthId'] = $me['id'];
        $_SESSION['oauthType'] = 'weibo';

        if(!empty($me['id'])) {

            /* 读取本站用户信息，检查connect会员是否绑定，已绑定直接登录，未绑定提示注册/绑定页面 */
            $r = $db->getRow("SELECT `user_id`,`user_name`,`password` FROM {$ecs->table('users')} WHERE `weibo_openid` = '{$me['id']}'");

            if(!empty($r))
            {
                /* 执行已绑定第三方登录 */
                oauthLogin($r);
                /* 登录成功跳转到首页 */
                header('location: index.php');
                exit;
            }
            else
            {
                /* 回调绑定页面 */
                $smarty->assign('direct_login', 'connect.php?act=direct_login&oauthType=weibo');
                $smarty->display('bind.dwt');
            }
        }else{
            /* 回调信息出错直接跳转至每三方登录 */
            header("Location:".$apiInfo->getAuthorizeURL($callback));
            exit;
        }
    }
    else
    {
        /* 非回调直接跳转至每三方登录 */
        header("Location:".$apiInfo->getAuthorizeURL($callback));
        exit;
    }
}

if($act == 'weixin')
{
    $appid = 'wx53cab4effc1c23f2';
    $appkey = 'c96aa708865b66b2848c86ed7b2250b9';
    $callback = 'http://'.$_SERVER['HTTP_HOST'].'/connect.php?act=weixin';

    require(ROOT_PATH . 'includes/weixinapi.class.php');
    $info = new weixinapi($appid,$appkey,$callback);

    if(!isset($_GET['code'])){
        $info->redirect_to_login();
    }else{
        $openid = $_SESSION['oauthId'] = $info->get_openid($_GET['code']);
        $_SESSION['oauthType'] = 'weixin';
        if(!empty($openid)){
            $r = $db->getRow("SELECT `user_id`,`user_name`,`email`,`password` FROM {$ecs->table('users')} WHERE `weixin_openid` = '$openid'");
            if(!empty($r)){
                /* 执行已绑定第三方登录 */
                oauthLogin($r);
                /* 登录成功跳转到首页 */
                header('location:index.php');
            }
            else
            {
                /* 回调绑定页面 */
                $smarty->assign('direct_login', 'connect.php?act=direct_login&oauthType=weixin');
                $smarty->display('bind.dwt');
            }
        }
        else
        {
            $info->redirect_to_login();
        }
    }

}

if($act == 'bind')
{

    if($_POST){

        include_once('includes/cls_json.php');
        $json = new JSON;

        $username = !empty($_POST['username']) ? json_str_iconv(trim($_POST['username'])) : '';
        $password = !empty($_POST['password']) ? trim($_POST['password']) : '';
        $captcha = !empty($_POST['captcha']) ? json_str_iconv(trim($_POST['captcha'])) : '';
        $result   = array('error' => 0, 'content' => '');

        if(!$username){
            $result['error']   = 1;
            $result['content'] = '请输入用户名！';
        }
        if(!$password){
            $result['error']   = 1;
            $result['content'] = '请输入密码！';
        }

        $captcha = intval($_CFG['captcha']);
        if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0)
        {
            if (empty($captcha))
            {
                $result['error']   = 1;
                $result['content'] = $_LANG['invalid_captcha'];
                die($json->encode($result));
            }

            /* 检查验证码 */
            include_once('includes/cls_captcha.php');

            $validator = new captcha();
            $validator->session_word = 'captcha_login';
            if (!$validator->check_word($_POST['captcha']))
            {
                $result['error']   = 1;
                $result['content'] = $_LANG['invalid_captcha'];
                die($json->encode($result));
            }
        }

        if ($user->login($username, $password,$_POST['remember']=1))
        {

            require_once(ROOT_PATH.'/plugins/ip/ip.php');
            $ip = new ip();
            $addr = $ip->ip2addr(real_ip());
            $errorlog = (time() . "\t" . $username."\t" . '0' . "\t" . real_ip()."\t". $addr['country']."\t". 'PC'."\t". get_user_browser()."\t"."登录并绑定第三方登录账号");
            writelog('cplogs', $errorlog);

            update_user_info();

            /* 登录成功并 绑定 openid */
            $db->query("UPDATE " . $ecs->table('users') . " SET `{$_SESSION['oauthType']}_openid` = '{$_SESSION['oauthId']}' WHERE `user_id`='{$_SESSION['user_id']}'");
            unset($_SESSION['oauthType'],$_SESSION['oauthId']);

            $smarty->assign('user_info', get_user_info());
            $ucdata = empty($user->ucdata)? "" : $user->ucdata;
            $result['ucdata'] = $ucdata;
            $result['content'] = $smarty->fetch('library/member_info.lbi');

        }
        else
        {
            require_once(ROOT_PATH.'/plugins/ip/ip.php');
            $ip = new ip();
            $addr = $ip->ip2addr(real_ip());
            $errorlog = (time()."\t".$username."\t".'0'."\t".real_ip()."\t".$addr['country']."\t".'PC'."\t".get_user_browser()."\t"."登录失败");

            writelog('cplogs', $errorlog);
            $result['error']   = 1;
            $result['content'] = '您输入的账号或密码不正确，请重新输入';
        }
        die($json->encode($result));
    }
    else
    {
        $smarty->assign('to_name',$_SESSION['qq_openid']?'QQ账号':($_SESSION['weibo_openid']?'新浪微博账号':'微信账号'));
        $smarty->display('bind.dwt');
    }

}

if($act == 'direct_login')
{
    if (empty($_SESSION['oauthId']) || empty($_SESSION['oauthId']) || in_array($_SESSION['oauthId'], array('qq', 'weixin', 'weibo'))) {
        // 如果不存在第三方ID则跳转到登录页面
        header('location: user.php');
        exit;
    }
    include_once(ROOT_PATH . 'includes/lib_passport.php');
    $username = $_REQUEST['oauthType'] . '_' . uniqid();
    $password = MD5($_SESSION['oauthId']);

    if (register($username, $password) !== false)
    {
        /* 注册成功并绑定 openid */
        $db->query("UPDATE {$ecs->table('users')} SET `{$_REQUEST['oauthType']}_openid` = '{$_SESSION['oauthId']}' WHERE `user_id`='{$_SESSION['user_id']}'");

        require_once(ROOT_PATH.'/plugins/ip/ip.php');
        $ip = new ip();
        $addr = $ip->ip2addr(real_ip());
        $errorlog = (time()."\t".$username."\t". '0'."\t".real_ip()."\t".$addr['country']."\t".'PC'."\t".get_user_browser()."\t"."注册成功并绑定");
        writelog('cplogs', $errorlog);

        /* 判断是否需要自动发送注册邮件 */
        header('location: user.php');
        exit;
    }
    else
    {
        require_once(ROOT_PATH.'/plugins/ip/ip.php');
        $ip = new ip();
        $addr = $ip->ip2addr(real_ip());
        $errorlog = (time()."\t".$username."\t".'0'."\t".real_ip()."\t".$addr['country']."\t".'PC'."\t".get_user_browser()."\t"."注册失败");
        writelog('cplogs', $errorlog);

        $result['error']   = 2;
        show_message(current($GLOBALS['err']->_message).'注册失败，请重新输入！');
    }
}

/**
  * 第三方已绑定登录
  * @param    arr     $r      已绑定会员信息
  */
function oauthLogin($r = array()) {
    /* 执行登录操作 */
    $_SESSION['user_id']        = $r['user_id'];
    $_SESSION['user_name']      = $r['user_name'];
    $_SESSION['user_order_num'] = $GLOBALS['db']->getOne("SELECT count(*) FROM " . $GLOBALS['ecs']->table('order_info') . " WHERE user_id={$_SESSION['user_id']}", true);

    require_once(ROOT_PATH.'/plugins/ip/ip.php');
    $ip = new ip();
    $addr = $ip->ip2addr(real_ip());
    $errorlog = (time()."\t".$username."\t".'0'."\t".real_ip()."\t".$addr['country']."\t".'PC'."\t".get_user_browser()."\t"."登录");
    writelog('cplogs', $errorlog);
    update_user_info();
}


